package com.example.questionservice.service.impl;

import com.example.questionservice.dao.QuestionRepository;
import com.example.questionservice.entity.Question;
import com.example.questionservice.entity.QuestionWrapper;
import com.example.questionservice.entity.Response;
import com.example.questionservice.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class QuestionServiceImpl implements QuestionService {
    @Autowired
    private QuestionRepository questionRepository;

    @Override
    public List<Question> getAllQuestions() {
        return questionRepository.findAll();
    }

    @Override
    public List<Question> getQuestionsByCategory(String category) {
        return questionRepository.findByCategory(category);
    }

     @Override
    public Question addQuestion(Question question) {
        return questionRepository.save(question);
    }

     @Override
    public List<Integer> generateQuestionsforQuiz(String category, int numOfQuestions) {
        List<Integer> questionIds = questionRepository.findRandomQuestionsByCategory(category, numOfQuestions);

        return questionIds;
    }

    @Override
    public List<QuestionWrapper> getQuestionsByIds(List<Integer> questionIds) {
        List<QuestionWrapper> wrappers = new ArrayList<>();
//        List<Question> questions = new ArrayList<>();

        for(Integer id : questionIds) {
            QuestionWrapper wrapper = new QuestionWrapper(
                    questionRepository.findById(id).get().getId(),
                    questionRepository.findById(id).get().getOption1(),
                    questionRepository.findById(id).get().getOption2(),
                    questionRepository.findById(id).get().getOption3(),
                    questionRepository.findById(id).get().getOption4(),
                    questionRepository.findById(id).get().getQuestionTitle()
            );
            wrappers.add(wrapper);
        }


        return wrappers;
    }

     @Override
    public Integer getScore(List<Response> responses) {
        int score = 0;
        for(Response response : responses) {
            String rightAnswer = questionRepository.findById(response.getId()).get().getRightAnswer();
            if(response.getResponse().equals(rightAnswer)) {
                score++;
            }
        }
        return score;
    }
}
